package work.kie.middle_exchange_repush;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;

import java.util.*;

/**
 * @author : Gong.Yang
 */
public class Main {
    public static void main(String[] args) {

        List<RepushObj> list = readDataFile();

        dataProcess(list);

        Map<String, String> requestHeader = new HashMap<>(16);
        requestHeader.put("Content-Type", "application/json; charset=utf-8");
        requestHeader.put("Authorization", Setting.token);

        for (RepushObj repushObj : list) {
            String body = null;
            try {
                body = HttpRequest.post(Setting.submitUrl)
                        .addHeaders(requestHeader)
                        .body(repushObj.getNewRequestBody())
                        .execute().body();
            } catch (Exception e) {
                body = e.getMessage() + e;
            }
            repushObj.setResponseBody(body);

            String paidResponseBody = null;
            try {
                String orderId = JSONUtil.parseObj(body).getJSONObject("data").getStr("orderId");
                JSONObject requestBody = new JSONObject();
                requestBody.set("orderId", orderId);
                requestBody.set("payTime", new Date());
                requestBody.set("totalRealPayPoints", 0);
                String jsonStr = JSONUtil.toJsonStr(requestBody);
                repushObj.setPaidRequestBody(jsonStr);
                paidResponseBody = HttpRequest.post(Setting.paidUrl)
                        .addHeaders(requestHeader)
                        .body(jsonStr).execute().body();
            }catch (Exception e){
                paidResponseBody = e.getMessage() + e;
            }
            repushObj.setPaidResponse(paidResponseBody);

        }
        EasyExcel.write(Setting.result, RepushObj.class).sheet().doWrite(list);
    }

    private static void dataProcess(List<RepushObj> list) {
        for (RepushObj repushObj : list) {
            repushObj.setNewOrderCode(repushObj.getOrderCode() + "_rerepush");
            repushObj.setNewRequestBody(repushObj.getRequestBody().replace(repushObj.getOrderCode(), repushObj.getNewOrderCode()));
        }
    }

    private static List<RepushObj> readDataFile() {
        List<RepushObj> list = new ArrayList<>();
        EasyExcel.read(Setting.data, RepushObj.class, new ReadListener<RepushObj>() {
            @Override
            public void invoke(RepushObj repushObj, AnalysisContext analysisContext) {
                list.add(repushObj);
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
//                System.out.println(list);
            }
        }).sheet().doRead();
        return list;
    }

}
